<template>
  <div class="fba-detail-wrap">
    <div class="header flex-c-sb">
      <a-space>
        <p>发货单详情</p>
        <span style="font-weight: bold">{{ fbaDetail.billNo }}</span>
        <span v-if="fbaDetail.urgent" class="urgent">急</span>
        <a-tag color="arcoblue" size="small" bordered>{{ statusMap[fbaDetail.status] }}</a-tag>
      </a-space>
      <div class="flex-c-c handle-btn-w">
        <a-space>
          <a-button class="gray-outline" size="medium" @click="closePage">关闭</a-button>
          <a-button v-if="fbaDetail.status == 'DRAFT' && $authPass('procurement.fba.shipment.sale.submit')" type="primary" size="medium" @click="submitAudit">提交处理</a-button>
          <a-button v-if="fbaDetail.status == 'INBOX' && $authPass('procurement.fba.shipment.sale.revokeDraft')" class="gray-outline" size="medium" @click="submitRevocationWait">撤回待处理</a-button>
          <a-button v-if="fbaDetail.status == 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.bind')" type="primary" size="medium" @click="showBindDialog = true">绑定货件</a-button>
          <a-button v-if="fbaDetail.status == 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.revokeInbox')" class="gray-outline" size="medium" @click="submitRevocationBox">撤回装箱中</a-button>
          <a-button v-if="['TO_BE_SHIPPED', 'SHIPPED', 'FINISHED', 'ERROR'].includes(fbaDetail.status)" class="gray-outline" size="medium" @click="syncFba">同步FBA货件</a-button>
        </a-space>
      </div>
    </div>
    <div class="flex">
      <div class="left-con">
        <div class="base">
          <p class="base-item">
            <span class="label">创建人：</span>
            <span class="val">{{ fbaDetail.createUname }}</span>
          </p>
          <p class="base-item">
            <span class="label">创建时间：</span>
            <span class="val">{{ $setTime(fbaDetail.gmtCreate) }}</span>
          </p>
          <p class="base-item">
            <span class="label">发货仓：</span>
            <span class="val">{{ $setTime(fbaDetail.warehouseName) }}</span>
          </p>
          <p class="base-item">
            <span class="label">发货地址：</span>
            <span class="val">{{ getAddress(fbaDetail.shipFromAddress) }}</span>
          </p>
          <p class="base-item">
            <span class="label">店铺：</span>
            <span class="val">{{ fbaDetail.shopName }}</span>
          </p>
          <p class="base-item">
            <span class="label">扣减包装库存：</span>
            <span class="val">{{ fbaDetail.needPackage ? '是' : '否' }}</span>
          </p>
          <p class="base-item">
            <span class="label">包装出货仓：</span>
            <span class="val">{{ fbaDetail.packageWarehouseName }}</span>
          </p>
          <div class="base-item">
            <span class="label">附件：</span>
            <ul style="margin-right: 10px" v-if="fbaDetail.attachment">
              <li v-for="(url, i) in fbaDetail.attachment.split(',')" style="margin-bottom: 4px" :key="i">
                <a-tag color="arcoblue" class="cursor" @click="downloadFile(url)">
                  <p class="text-limit" style="width: 150px">{{ url }}</p>
                  <icon-to-bottom />
                </a-tag>
              </li>
            </ul>
          </div>
          <p class="base-item">
            <span class="label">备注：</span>
            <span class="val">{{ fbaDetail.remark }}</span>
          </p>
        </div>
        <div class="ama-fba" v-if="fbaDetail.shipmentId" style="margin-top: 20px">
          <p class="base-item">
            <span class="label">FBA货件号：</span>
            <span class="val">{{ fbaDetail.shipmentId }}</span>
          </p>
          <p class="base-item">
            <span class="label">FBA货件名称：</span>
            <span class="val">{{ fbaDetail.shipmentName }}</span>
          </p>
          <p class="base-item">
            <span class="label">CenterId：</span>
            <span class="val">{{ fbaDetail.centerId }}</span>
          </p>
          <p class="base-item">
            <span class="label">状态：</span>
            <span class="val">{{ fbaDetail.amzStatus }}</span>
          </p>
          <p class="base-item">
            <span class="label">贴标方：</span>
            <span class="val">{{ fbaDetail.labelPrepType == 'SELLER_LABEL' ? '卖家' : '买家' }}</span>
          </p>
          <p class="base-item">
            <span class="label">包装方式：</span>
            <span class="val">{{ fbaDetail.boxContentsSource }}</span>
          </p>
          <p class="base-item">
            <span class="label">收货地址：</span>
            <span class="val">{{ getAddress(fbaDetail.shipToAddress) }}</span>
          </p>
          <div class="base-item" v-if="['SHIPPED', 'TO_BE_SHIPPED'].includes(fbaDetail.status)">
            <span class="label">箱单：</span>
            <div>
              <icon-printer />
              <a-button size="mini" type="text" @click="showPrintBox = true">打印装箱单</a-button>
            </div>
          </div>
        </div>
        <div class="logistics" style="margin-top: 20px" v-if="fbaDetail.status != 'DRAFT'">
          <p class="base-item">
            <span class="label">物流方式：</span>
            <span class="val" v-if="$extract(fbaDetail, 'logisticsInfo.logisticType')">{{ $extract(fbaDetail, 'logisticsInfo.logisticType') == 1 ? 'API' : '自定义' }}</span>
          </p>
          <p class="base-item">
            <span class="label">物流商：</span>
            <span class="val">{{ $extract(fbaDetail, 'logisticsInfo.logisticName') }}</span>
          </p>
          <p class="base-item">
            <span class="label">渠道：</span>
            <span class="val">{{ $extract(fbaDetail, 'logisticsInfo.logisticChannelName') }}</span>
          </p>
          <p class="base-item">
            <span class="label">承运商：</span>
            <span class="val">{{ $extract(fbaDetail, 'logisticsInfo.carrierName') }}</span>
          </p>
          <p class="base-item">
            <span class="label">运单号：</span>
            <span class="val">{{ $extract(fbaDetail, 'logisticsInfo.logisticsWaybillNumber') }}</span>
          </p>
          <p class="base-item">
            <span class="label">跟踪号：</span>
            <span class="val">{{ $extract(fbaDetail, 'logisticsInfo.logisticsTrackNumber') }}</span>
          </p>
          <div class="base-item">
            <span class="label">物流面单：</span>
            <div v-if="$extract(fbaDetail, 'logisticsInfo.logisticsManifest')">
              <icon-printer />
              <a-button size="mini" type="text" @click="openLogisticsManifest(fbaDetail)">打印面单</a-button>
            </div>
            <span class="val" v-else>--</span>
          </div>
        </div>
      </div>
      <div class="right-con">
        <a-steps :current="currentStep">
          <a-step>
            <template #description>
              <p>{{ $setTime(fbaDetail.gmtCreate) }}</p>
            </template>
            创建发货单
          </a-step>
          <a-step>
            <template #description>
              <p v-if="currentStep > 2 && fbaDetail.gmtSubmit">{{ $setTime(fbaDetail.gmtSubmit) }}</p>
            </template>
            提交处理
          </a-step>
          <a-step>
            <template #description>
              <p v-if="fbaDetail.gmtTransToBeShipped">{{ $setTime(fbaDetail.gmtTransToBeShipped) }}</p>
            </template>
            转待发货
          </a-step>
          <a-step>
            <template #description>
              <p v-if="fbaDetail.gmtShipped">{{ $setTime(fbaDetail.gmtShipped) }}</p>
            </template>
            确认发货
          </a-step>
          <a-step>
            <template #description v-if="fbaDetail.gmtFinished">
              <p>{{ $setTime(fbaDetail.gmtFinished) }}</p>
            </template>
            已入库
          </a-step>
        </a-steps>
        <a-tabs style="margin: 20px 0" v-model:active-key="activeTab">
          <a-tab-pane key="1" title="发货单明细" />
          <a-tab-pane key="2" title="装箱明细" />
          <a-tab-pane key="3" title="操作日志" />
        </a-tabs>
        <div class="detail-item">
          <FbaDetailtems v-if="activeTab == '1'" :fbaDetail="fbaDetail" :list="fbaDetail.skuDetails" @success="getFbaDetail" />
          <FbaDetailBoxItems v-if="activeTab == '2'" :list="fbaDetail.boxDetails" />
          <PurchaseLogs v-if="activeTab == '3'" api="findFbaShipmentLogPage" :currentData="fbaDetail" />
        </div>
      </div>
    </div>
  </div>
  <!-- 绑定FBA货件 -->
  <BindFbaCode v-if="showBindDialog" source="sale" :isShow="showBindDialog" :currentData="fbaDetail" @closed="showBindDialog = false" @success="getFbaDetail" />
  <!-- 打印装箱单 -->
  <PrintFbaBox v-if="showPrintBox" :isShow="showPrintBox" :currentData="fbaDetail" @closed="showPrintBox = false" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { useRouter, useRoute } from 'vue-router'
  import FbaDetailtems from './components/fbaDetailItems.vue'
  import FbaDetailBoxItems from './components/fbaDetailBoxItems.vue'
  import { getFbaShipmentInfo, submitFbaShipmentBySale, revokeFbaShipmentToDraftBySale, revokeFbaShipmentToInboxBySale, syncFbaShipmentAmazon } from '@/api/purchase'
  import BindFbaCode from './components/bindFbaCode.vue'
  import PurchaseLogs from '@/views/purchaseApplication/components/purchaseLogs.vue'
  import PrintFbaBox from '@/views/warehouse/fbaDelivery/components/printFbaBox.vue'
  onMounted(() => {
    getFbaDetail()
  })

  const statusMap = {
    DRAFT: '待处理',
    INBOX: '装箱中',
    TO_BE_BIND: '绑定货件',
    TO_BE_SHIPPED: '待发货',
    SHIPPED: '已发货',
    FINISHED: '已入库',
    ERROR: '取消/异常',
  }
  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const showBindDialog = ref(false)
  const fbaDetail = ref<any>({})
  const currentStep = ref(1)
  const activeTab = ref('1')
  const showPrintBox = ref(false)

  // 获取采购订单详情
  async function getFbaDetail() {
    const res: any = await getFbaShipmentInfo({ id: route.query.id })
    fbaDetail.value = res?.data || {}
    let status = fbaDetail.value.status
    if (status == 'DRAFT') {
      currentStep.value = 2
    } else if (status == 'INBOX' || status == 'TO_BE_BIND') {
      currentStep.value = 3
    } else if (status == 'SHIPPED' || status == 'TO_BE_SHIPPED') {
      currentStep.value = 4
    } else {
      currentStep.value = 5
    }
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.push('/purchase/fbaManagement/deliveryList')
  }
  // 提交处理
  function submitAudit() {
    Modal.confirm({
      title: '提交处理',
      content: `请再次确认是否将该发货单提交处理`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await submitFbaShipmentBySale({ ids: [fbaDetail.value.id] })
        if (res) {
          Message.success('提交处理成功')
          getFbaDetail()
        }
      },
    })
  }
  // 撤回待处理
  function submitRevocationWait() {
    Modal.confirm({
      title: '撤回待处理',
      content: `请再次确认是否将该发货单撤回到待处理状态`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeFbaShipmentToDraftBySale({ ids: [fbaDetail.value.id] })
        if (res) {
          Message.success('撤回成功')
          getFbaDetail()
        }
      },
    })
  }
  // 撤回装箱中
  function submitRevocationBox() {
    Modal.confirm({
      title: '撤回装箱中',
      content: `请再次确认是否将该发货单撤回到装箱中状态`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeFbaShipmentToInboxBySale({ ids: [fbaDetail.value.id] })
        if (res) {
          Message.success('撤回成功')
          getFbaDetail()
        }
      },
    })
  }
  // 同步FBA货件
  function syncFba() {
    Modal.confirm({
      title: '同步FBA货件',
      content: `请再次确认是否需要同步货件:${fbaDetail.value.billNo}`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await syncFbaShipmentAmazon({ ids: [fbaDetail.value.id] })
        if (res) {
          Message.success('同步成功')
          getFbaDetail()
        }
      },
    })
  }
  // 显示地址
  function getAddress(address: any) {
    return `${address?.countryCode || ''}${address?.stateOrProvinceCode || ''}${address?.city || ''}${address?.addressLine1 || ''}`
  }
  // 打印物流面单
  function openLogisticsManifest(row: any) {
    let url = row?.logisticsInfo?.logisticsManifest
    window.open(url, '_block')
  }
  //  下载
  function downloadFile(url: string) {
    let _url = url
    if (_url.indexOf('?') > -1) {
      _url += '&response-content-type=application/octet-stream'
    } else {
      _url += '?response-content-type=application/octet-stream'
    }
    let link = document.createElement('a')
    link.href = _url
    link.click()
  }
</script>
<style lang="less" scoped>
  .fba-detail-wrap {
    height: calc(100vh - @menuHeight);
    display: flex;
    flex-direction: column;
    .urgent {
      font-size: 12px;
      background-color: red;
      color: #fff;
      width: 18px;
      border-radius: 50%;
      line-height: 18px;
      text-align: center;
      transform: scale(0.82);
    }
    .header {
      padding: 10px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .left-con {
      width: 320px;
      margin-right: 10px;
      background-color: #fff;
      min-height: calc(100vh - 150px);
      flex-shrink: 0;
      padding: 20px;
      .base-item {
        display: flex;
        margin-bottom: 5px;
        .label {
          width: 100px;
          text-align: right;
          flex-shrink: 0;
          color: #666;
        }
      }
    }
    .right-con {
      background-color: #fff;
      flex: 1;
      padding: 20px;
      overflow: hidden;
      .detail-item {
        overflow: hidden;
        height: calc(100vh - 320px);
      }
    }
  }
</style>
